import {defineStore} from 'pinia'
import {login, logout, getUserInfo as getInfo, register} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {getMenuList, getRoleMenuIds} from '@/api/admin/menu'

export const useUserStore = defineStore('user', {
    state: () => ({
        token: getToken(),
        id: null,
        name: '',
        avatar: '',
        roles: [],
        permissions: [],
        menuList: [],
        role: ''
    }),

    getters: {
        isLoggedIn: (state) => !!state.token,
        isAdmin: (state) => state.roles?.includes('admin') || false
    },

    actions: {
        // 登录
        async login({name, password, role}) {
            try {
                const response = await login(name.trim(), password)
                const {data} = response
                this.token = data.token
                setToken(data.token)
                this.role = role
                if (role === 'admin') {
                    const res = await getMenuList()
                    if (res.code === 200) {
                        this.menuList = res.data
                    } else {
                        this.menuList = []
                    }
                } else if (role === 'leader') {
                    const res = await getRoleMenuIds(2)
                    if (res.code === 200) {
                        const allMenus = await getMenuList()
                        if (allMenus.code === 200) {
                            this.menuList = allMenus.data.filter(menu => res.data.includes(menu.id))
                        } else {
                            this.menuList = []
                        }
                    } else {
                        this.menuList = []
                    }
                } else {
                    this.menuList = []
                }
                return Promise.resolve()
            } catch (error) {
                return Promise.reject(error)
            }
        },

        // 获取用户信息
        async getInfo() {
            try {
                const response = await getInfo()
                const {data} = response

                if (!data) {
                    return Promise.reject('验证失败，请重新登录')
                }

                const {id, name, avatar, roles, role} = data

                this.id = id
                this.name = name
                this.avatar = avatar
                this.roles = roles
                this.role = role
                console.log(22222222222)
                console.log(role)

                return Promise.resolve(data)
            } catch (error) {
                return Promise.reject(error)
            }
        },

        // 登出
        async logout() {
            try {
                await logout()
                this.resetState()
                return Promise.resolve()
            } catch (error) {
                return Promise.reject(error)
            }
        },

        // 重置状态
        resetState() {
            this.token = ''
            this.id = null
            this.name = ''
            this.avatar = ''
            this.roles = []
            this.permissions = []
            this.menuList = []
            this.role = ''
            removeToken()
        },

        // 注册用户
        async register(userInfo) {
            try {
                const response = await register(userInfo)
                return Promise.resolve(response.data)
            } catch (error) {
                return Promise.reject(error)
            }
        }
    },

    persist: {
        enabled: true,
        strategies: [
            {
                key: 'user',
                storage: localStorage,
                paths: ['token']
            }
        ]
    }
})
